package m5;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");  // wht6.cn
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        // 1.随机队列 2.交换机 3.绑定，设置绑定键
        // 由服务器来自动提供队列参数: 随机命名,false,true,true
        String queue = c.queueDeclare().getQueue();
        c.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);

        System.out.println("输入绑定键，用空格隔开：");// "aa    bb cc dd"
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");  //  \s是空白字符   +一到多个
        for (String k : a) {
            c.queueBind(queue, "topic_logs", k);
        }
        // 接收消息
        DeliverCallback deliverCallback = new DeliverCallback() {
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                // 消息携带的路由键
                String k = message.getEnvelope().getRoutingKey();
                System.out.println(k+" --- 收到： "+s);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            public void handle(String consumerTag) throws IOException {
            }
        };
        c.basicConsume(queue, true, deliverCallback,cancelCallback);
    }
}
